import React, { useEffect, useState } from 'react';
import { 
  Button, Table, message, Popconfirm, Form, Input, Select, 
  Row, Col, Card, Space, Tag 
} from 'antd';
import '../components.css';
import CollectionsService from '../../services/CollectionsService';
import { Link } from 'react-router-dom';
import { 
  DeleteOutlined, EyeOutlined, PlusOutlined, 
  ExportOutlined, ImportOutlined, SearchOutlined, SyncOutlined 
} from '@ant-design/icons';

const { Option } = Select;

export default function CollectionList() {
  const [collections, setCollections] = useState([]);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  useEffect(() => {
    fetchCollections();
  }, []);

  const fetchCollections = () => {
    setLoading(true);
    CollectionsService.getAllCollections()
      .then(response => {
        setCollections(response.data);
        setLoading(false);
      })
      .catch(error => {
        console.log(error);
        setLoading(false);
      });
  };

  const handleSearch = (values) => {
    setLoading(true);
    CollectionsService.searchCollections({
      orderId: values.orderId,
      approvalStatus: values.approvalStatus,
      overdueStatus: values.overdueStatus,
      paymentMethod: values.paymentMethod
    })
    .then(response => {
      setCollections(response.data);
      setLoading(false);
    })
    .catch(error => {
      message.error('搜索失败');
      setLoading(false);
    });
  };

  const handleReset = () => {
    form.resetFields();
    fetchCollections();
  };

  const deleteCollection = (id) => {
    CollectionsService.deleteCollection(id)
      .then(() => {
        message.success('删除成功!');
        fetchCollections();
      })
      .catch(error => {
        message.error('删除失败!');
      });
  };

  const columns = [
    {
      title: '系统编号',
      dataIndex: 'id',
      key: 'id',
      align: 'center',
      width: 100,
    },
    {
      title: '关联订单',
      dataIndex: 'orderId',
      key: 'orderId',
      align: 'center',
      width: 150,
    },
    {
      title: '回款日期',
      dataIndex: 'collectionDate',
      key: 'collectionDate',
      align: 'center',
      width: 120,
    },
    {
      title: '回款期次',
      dataIndex: 'period',
      key: 'period',
      align: 'center',
      width: 100,
    },
    {
      title: '付款方式',
      dataIndex: 'paymentMethod',
      key: 'paymentMethod',
      align: 'center',
      width: 120,
    },
    {
      title: '审批状态',
      dataIndex: 'approvalStatus',
      key: 'approvalStatus',
      align: 'center',
      width: 120,
      render: status => (
        <Tag 
          color={
            status === '已通过' ? 'green' : 
            status === '被否决' || status === '被驳回' ? 'red' : 
            status === '已撤销' ? 'orange' : 'blue'
          }
        >
          {status}
        </Tag>
      )
    },
    {
      title: '回款金额',
      dataIndex: 'amount',
      key: 'amount',
      align: 'center',
      width: 120,
      render: amount => `¥ ${parseFloat(amount).toFixed(2)}`
    },
    {
      title: '逾期状态',
      dataIndex: 'overdueStatus',
      key: 'overdueStatus',
      align: 'center',
      width: 100,
      render: status => (
        <Tag color={status === '逾期' ? 'red' : 'green'}>
          {status}
        </Tag>
      )
    },
    {
      title: '操作',
      key: 'actions',
      align: 'center',
      width: 180,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Button 
            type="primary" 
            size="small" 
            icon={<EyeOutlined />}
          >
            <Link to={`/collectiondetail/${record.id}`}>详情</Link>
          </Button>
          <Popconfirm
            title="确定删除此回款记录吗?"
            onConfirm={() => deleteCollection(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="danger" size="small" icon={<DeleteOutlined />}>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const data = collections.map(item => ({
    key: item.id,
    ...item
  }));

  const rowSelection = {
    selectedRowKeys,
    onChange: setSelectedRowKeys,
  };

  return (
    <div className='collection-list-container'>
      <Card
        title="回款管理"
        bordered={false}
        extra={
          <Button type="primary" icon={<PlusOutlined />}>
            <Link to="/addcollection">添加回款</Link>
          </Button>
        }
      >
        <Form form={form} onFinish={handleSearch} layout="inline">
          <Row gutter={24} style={{ marginBottom: 16 }}>
            <Col span={6}>
              <Form.Item name="orderId" label="订单ID">
                <Input placeholder="输入订单ID" allowClear />
              </Form.Item>
            </Col>
            
            <Col span={6}>
              <Form.Item name="approvalStatus" label="审批状态">
                <Select placeholder="全部状态" allowClear>
                  <Option value="待审批">待审批</Option>
                  <Option value="已通过">已通过</Option>
                  <Option value="被否决">被否决</Option>
                  <Option value="被驳回">被驳回</Option>
                  <Option value="已撤销">已撤销</Option>
                </Select>
              </Form.Item>
            </Col>
            
            <Col span={6}>
              <Form.Item name="overdueStatus" label="逾期状态">
                <Select placeholder="全部状态" allowClear>
                  <Option value="正常">正常</Option>
                  <Option value="逾期">逾期</Option>
                </Select>
              </Form.Item>
            </Col>
            
            <Col span={6}>
              <Form.Item name="paymentMethod" label="付款方式">
                <Select placeholder="全部方式" allowClear>
                  <Option value="现金">现金</Option>
                  <Option value="银行转账">银行转账</Option>
                  <Option value="支付宝">支付宝</Option>
                  <Option value="微信支付">微信支付</Option>
                </Select>
              </Form.Item>
            </Col>
            
            <Col span={24} style={{ textAlign: 'right', marginTop: 8 }}>
              <Button 
                type="primary" 
                icon={<SearchOutlined />} 
                htmlType="submit"
                style={{ marginRight: 8 }}
              >
                查询
              </Button>
              <Button 
                icon={<SyncOutlined />} 
                onClick={handleReset}
                style={{ marginRight: 8 }}
              >
                重置
              </Button>
              <Button icon={<ExportOutlined />} style={{ marginRight: 8 }}>导出</Button>
              <Button icon={<ImportOutlined />}>导入</Button>
            </Col>
          </Row>
        </Form>

        <Table
          columns={columns}
          dataSource={data}
          rowSelection={rowSelection}
          loading={loading}
          scroll={{ x: 1300 }}
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: total => `共 ${total} 条`,
            pageSizeOptions: ['10', '20', '50', '100']
          }}
        />
      </Card>
    </div>
  );
}